<template>
  <view class="container">
    <view class="orderBox">
      <image :src="getProductImage(order_detail.img)" class="orderImg"></image>
      <view class="orderInfo">
        <view class="orderName">{{ order_detail.title }}</view>
        <view class="orderMonthlySales">月售 {{ monthlySales }}</view>

        <view class="orderPrice">
          <view class="orderPriceNumber">￥{{ order_detail.price }}</view>
          <view class="orderPriceUnit">x {{ quantity }}</view>
        </view>
      </view>
    </view>

    <view class="orderDetail">
      <view class="orderDetail_item">
        <view style="font-weight: bold;font-size:14px; color: #999;">商品金额</view>
        <view class="orderPriceNumber">￥{{ totalPrice.toFixed(2) }}</view>
      </view>

      <view class="orderDetail_item" style="margin-top: 3%;">
        <view style="font-weight: bold;font-size:14px; color: #999;">支付方式</view>
        <view class="orderPriceNumber WechatPay">微信支付</view>
      </view>

      <view class="orderDetail_item" style="margin-top: 3%;">
        <view style="font-weight: bold;font-size:14px; color: #999;">商品数量</view>
        <view class="quantity-controller">
          <view class="quantity-btn" @click="decreaseQuantity">-</view>
          <input class="quantity-input" v-model="quantity" type="number" />
          <view class="quantity-btn" @click="increaseQuantity">+</view>
        </view>
      </view>
    </view>

    <view class="Attention_box">
      <view style="text-indent: 10px; color:rgba(255, 141, 26, 1); font-size: 14px;margin-top:3%">
        注意：购买后一定要注音您的单号的使用时间，过时概不负责！！！！
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer_box">
      <view class="operate_box">
        <view class="total_price">合计:￥{{ totalPrice.toFixed(2) }}</view>
        <view class="total_num">共 {{ quantity }} 件</view>
      </view>

      <view class="buyButton_box">
        <view class="buy_shop">
          <button class="submit-order-btn" @click="showConfirmDialog">提交订单</button>
        </view>
      </view>
    </view>

    <!-- 自定义弹窗 -->
    <view v-if="showModal" class="custom-modal">
      <view class="custom-modal-mask"></view>
      <view class="custom-modal-content">
        <view class="custom-modal-header">
          <view class="custom-modal-title">提示</view>
        </view>
        <view class="custom-modal-body">
          您是否确定订单？
        </view>
        <view class="custom-modal-footer">
          <view class="custom-modal-button cancel" @click="cancelOrder">取消</view>
          <view class="custom-modal-button confirm" @click="confirmOrder">确定</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/static/config.js';
export default {
  data() {
    return {
      order_detail: {},
      monthlySales: 0,
      shopID: 0,
      quantity: 1,
      unitPrice: 0,
      showModal: false,
      defaultImage: config.imgUrl + '/img/icons1.png',
      baseURL: 'https://yikatong.kuxia.top', // 默认baseURL
      token: '', // 用户token
      userId: '' // 用户ID
    };
  },
  
  computed: {
    // 计算总价
    totalPrice() {
      return this.unitPrice * this.quantity;
    }
  },
  
  onLoad() {
    // 从本地存储获取商品信息
    try {
      const product = uni.getStorageSync('selectedProduct');
      
      if (product) {
        this.order_detail = product;
        this.unitPrice = parseFloat(product.price || product.money || 0);
        this.monthlySales = product.quantity || 0;
        // 修复：使用正确的字段名 foodshop_id
        this.shopID = product.foodshop_id || 0;
        this.quantity = 1;
        
      } else {
        uni.showToast({
          title: '未选择商品',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      }
      
      // 尝试从配置文件获取baseURL
      this.loadBaseURL();
      
      // 获取用户信息
      this.loadUserInfo();
    } catch (e) {
      console.error('获取商品信息失败:', e);
    }
  },
  
  methods: {
    // 加载配置文件中的baseURL
    loadBaseURL() {
      try {
        const config = require('../../static/config.js').default;
        if (config && config.baseURL) {
          this.baseURL = config.baseURL;
        }
      } catch (e) {
        console.warn('无法加载配置文件，使用默认baseURL:', e);
      }
    },
    
    // 加载用户信息
    loadUserInfo() {
      try {
        // 从本地存储获取用户token和ID
        this.token = uni.getStorageSync('token') || '';
        this.userId = uni.getStorageSync('userId') || '';
        
        // 如果本地存储中没有，可能需要从其他地方获取
        if (!this.token || !this.userId) {
          console.warn('用户未登录或缺少用户信息');
        }
      } catch (e) {
        console.error('获取用户信息失败:', e);
      }
    },
    
    // 获取商品图片
    getProductImage(imgUrl) {
      if (!imgUrl) return this.defaultImage;
      
      // 如果已经是完整URL，直接返回
      if (imgUrl.startsWith('http://') || imgUrl.startsWith('https://')) {
        return imgUrl;
      }
      
      // 如果是相对路径，拼接基础URL
      return this.baseURL + imgUrl;
    },
    
    // 增加数量
    increaseQuantity() {
      this.quantity++;
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },
    
    // 数量变化处理
    handleQuantityChange(value) {
      if (value >= 1) {
        this.quantity = parseInt(value);
      }
    },
    
    // 显示确认对话框
    showConfirmDialog() {
      this.showModal = true;
    },
    
    // 取消订单
    cancelOrder() {
      this.showModal = false;
    },
    
    // 确认订单
    confirmOrder() {
      this.showModal = false;
      this.submitOrder();
    },
    
    // 提交订单
    submitOrder() {
      // 重新从本地存储获取用户信息，确保获取最新数据
      const token = uni.getStorageSync('token') || '';
      const userId = uni.getStorageSync('userId') || '';
      this.token = token;
      this.userId = userId;
      
      // 检查用户是否已登录
      if (!token || !userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        // 跳转到登录页面
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/login/login'
          });
        }, 1500);
        return;
      }
      
      // 构造请求参数
      const uid = userId; // 使用实际用户ID
      const arr = [{
        // 修复：使用正确的字段 this.shopID 而不是 this.foodshop_id
        shop_id: this.shopID,
        product: [{
          product_id: this.order_detail.id,
          price: this.order_detail.price,
          num: this.quantity
        }]
      }];
      
      
      // 引入统一封装的API
      const { foodAPI } = require('../../static/indexAPI.js');
      
      // 发起支付请求
      foodAPI.submitOrder({
        uid: uid,
        arr: JSON.stringify(arr) // 根据接口要求，可能需要转换为字符串
      }, token).then((res) => {
        // 处理响应结果
        const responseData = res.data || res;
        
        if (responseData.code == 1 || responseData.status == 1) {
          // 请求成功，提示用户并跳转到支付成功页面
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });
          
          // 存储订单总价格和商店ID供支付成功页面使用
          uni.setStorageSync('order_total_price', this.totalPrice);
          // 修复：存储正确的 shopID 而不是 this.foodshop_id
          uni.setStorageSync('shopID', this.shopID);
          uni.setStorageSync('currentProductId', this.order_detail.id);
          
          
          // 跳转到支付成功页面
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/goodsuccess/goodsuccess'
            });
          }, 1500);
        } else if (responseData.code == 401 || responseData.status == 401) {
          // Token失效
          uni.removeStorageSync('token');
          uni.removeStorageSync('userId');
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/login/login'
            });
          }, 1500);
        } else {
          // 请求成功但业务处理失败
          uni.showToast({
            title: responseData.message || responseData.msg || '支付失败',
            icon: 'none'
          });
        }
      }).catch((err) => {
        // 请求失败
        uni.showToast({
          title: '请求失败，请重试',
          icon: 'none'
        });
        console.error('支付请求失败:', err);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px;
}

.orderBox {
  width: 95%;
  height: 120px;
  display: flex;
  margin-top: 2%;
  margin-left: 2.5%;
  border-radius: 5px;
  background-color: white;
}

.orderImg {
  width: 95px;
  height: 95px;
  margin-top: 3%;
  margin-left: 2%;
  border-radius: 5px;
}

.orderInfo {
  width: 80%;
  height: 120px;
}

.orderName {
  font-size: 16px;
  line-height: 45px;
  text-indent: 10px;
}

.orderMonthlySales {
  font-size: 14px;
  line-height: 25px;
  text-indent: 10px;
  color: #999;
}

.orderPrice {
  width: 90%;
  display: flex;
  justify-content: space-between;
  text-indent: 10px;
  line-height: 45px;
}

.orderPriceNumber {
  font-size: 14px;
  font-weight: bold;
  color: red;
}

.WechatPay {
  color: #999;
}

.orderPriceUnit {
  font-size: 14px;
  font-weight: bold;
  color: #999;
}

.orderDetail {
  width: 95%;
  height: 145px;
  margin-top: 2%;
  margin-left: 2.5%;
  border-radius: 5px;
  background-color: white;
}

.orderDetail_item {
  width: 90%;
  height: 30px;
  margin-left: 4%;
  display: flex;
  line-height: 50px;
  justify-content: space-between;
  align-items: baseline;
}

.quantity-controller {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 30px;
}

.quantity-btn {
  width: 25px;
  height: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #AAD2CF;
  background-color: #fff;
  border: 1px solid #AAD2CF;
  border-radius: 50%;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
}

.quantity-input {
  width: 40px;
  height: 25px;
  text-align: center;
  border-left: none;
  border-right: none;
  font-size: 14px;
  margin: 0;
  padding: 0;
}

.footer_box {
  width: 100%;
  height: 70px;
  position: fixed;
  bottom: 0;
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #f5f5f5;
}

.operate_box {
  width: 30%;
}

.operate_img {
  width: 35px;
  height: 35px;
  margin-top: 50%;
  margin-left: 14%;
}

.buyButton_box {
  width: 30%;
  margin-right: 3%;
  margin-top: 2%;
}

.buy_shop {
  margin-top: 5%;
  height: 50px;
}

.submit-order-btn {
  height: 35px;
  line-height: 35px;
  background-color: rgba(254, 115, 32, 1);
  color: white;
  border-radius: 20px;
  border: none;
  font-size: 14px;
  width: 100%;
}

.total_price {
  font-size: 15px;
  font-weight: bold;
  text-indent: 10px;
  line-height: 45px;
  color: #fe7320;
  white-space: nowrap;
}

.total_num {
  font-size: 13px;
  font-weight: bold;
  text-indent: 10px;
  line-height: 5px;
}

/* 自定义弹窗样式 */
.custom-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.custom-modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.custom-modal-content {
  width: 80%;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  z-index: 10000;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.custom-modal-header {
  padding: 15px;
  text-align: center;
  border-bottom: 1px solid #eee;
}

.custom-modal-title {
  font-size: 16px;
  color: rgba(0, 0, 0, 1);
}

.custom-modal-body {
  padding: 20px;
  text-align: center;
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
}

.custom-modal-footer {
  display: flex;
  border-top: 1px solid #eee;
}

.custom-modal-button {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
}

.custom-modal-button.cancel {
  border-right: 1px solid #eee;
  color: rgba(80, 80, 80, 1);
}

.custom-modal-button.confirm {
  color: rgba(80, 80, 80, 1);
  font-weight: bold;
}

.Attention_box {
  width: 100%;
  height: 60px;
  position: fixed;
  bottom: 74px;
  background-color: rgba(255, 195, 0, 0.2);
}
</style>